package msu.ml.gis;

import java.util.*;
import java.awt.geom.Rectangle2D;

/**
 * The PulseVolumeShape class represents a four sided
 * polygon in the GIS system. This shape translates
 * to the pulse volume found in a Nexrad Sweep.
 *
 * @author Reginald M Mead
 * @version 1.0
 */
public class PulseVolumeShape extends Polygon 
{

    public static final double RADIUS = 150000.0;
	/**
	 * Create a new PulseVolumeShape at the specified azimuth and
	 * range. 
	 *
	 * @param sfile Shapefile to use for translating points
	 * to correct latitude and longitude
	 * @param azimuth Azimuth of pulse volume in degrees
	 * @param range range of this pulse volume in meters
	 */
	public PulseVolumeShape(Shapefile sfile, double azimuth, double range)
	{
		Point p1, p2, p3, p4, p5; //Clockwise starting with inside at azimuth
		p1 = new Point(cX(range, azimuth), cY(range, azimuth));
		p2 = new Point(cX(range+1000, azimuth), cY(range+1000, azimuth));
		p3 = new Point(cX(range+1000, azimuth + 1.0), cY(range+1000, azimuth + 1.0));
		p4 = new Point(cX(range, azimuth + 1.0), cY(range, azimuth + 1.0));
		//repeat p1 to close polygon
		p5 = new Point(cX(range, azimuth), cY(range, azimuth));

		/*p1 = sfile.getGeographicalPoint(p1);
		p2 = sfile.getGeographicalPoint(p2);
		p3 = sfile.getGeographicalPoint(p3);
		p4 = sfile.getGeographicalPoint(p4);
		p5 = sfile.getGeographicalPoint(p5);*/
		
		m_Point.add(p1);
		m_Point.add(p2);
		m_Point.add(p3);
		m_Point.add(p4);
		m_Point.add(p5);

		double minX = smallestX(p1,p2,p3,p4);
		double minY = smallestY(p1,p2,p3,p4);
		double maxX = biggestX(p1,p2,p3,p4);
		double maxY = biggestY(p1,p2,p3,p4);

		boundingBox = new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY);
	}

    private double cX(double r, double t)
    {
		return RADIUS - Math.rint(r * Math.cos(t * Math.PI / 180.0));
    }

    private double cY(double r, double t)
    {
		return Math.rint(r * Math.sin(t * Math.PI / 180.0)) + RADIUS;
    }

	private double biggestX(Point a, Point b, Point c, Point d)
	{
		double result = a.getX();
		if(b.getX() > result) result= b.getX();
		if(c.getX() > result) result= c.getX();
		if(d.getX() > result) result= d.getX();
		return result;
	}

	private double biggestY(Point a, Point b, Point c, Point d)
	{
		double result = a.getY();
		if(b.getY() > result) result= b.getY();
		if(c.getY() > result) result= c.getY();
		if(d.getY() > result) result= d.getY();
		return result;

	}

	private double smallestX(Point a, Point b, Point c, Point d)
	{
		double result = a.getX();
		if(b.getX() < result) result= b.getX();
		if(c.getX() < result) result= c.getX();
		if(d.getX() < result) result= d.getX();
		return result;
	}

	private double smallestY(Point a, Point b, Point c, Point d)
	{
		double result = a.getY();
		if(b.getY() < result) result= b.getY();
		if(c.getY() < result) result= c.getY();
		if(d.getY() < result) result= d.getY();
		return result;
	}


}
